package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/*
* @Description: TODO
* @Author: YangTing
* @Date: 2023/5/22 15:24
**/
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        //缓存空对象解决缓存穿透
        Shop shop = cacheClient.queryWidthPassThrough(
                CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //互斥锁方式解决缓存击穿
//        Shop shop = queryWithMutex(id);
        //逻辑过期方式解决缓存击穿
//        Shop shop = queryWithLogicalExpire(id);
        //使用封装的逻辑过期解决缓存击穿
//        Shop shop = cacheClient.queryWithLogicalExpire(
//                CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);
        if (shop == null) {
            return Result.fail("店铺不存在哦~");
        }
        return Result.ok(shop);
    }

    public static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //逻辑过期方式，解决缓存击穿
    public Shop queryWithLogicalExpire(Long id){
        String key = CACHE_SHOP_KEY + id;
        String shopMessage = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(shopMessage)) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(shopMessage, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        if(expireTime.isAfter(LocalDateTime.now())){
            return shop;
        }
        String lockKey = LOCK_SHOP_KEY + id;
        Boolean isLock = tryLock(lockKey);
        if (isLock) {
            CACHE_REBUILD_EXECUTOR.submit(() ->{
                try {
                    saveShopRedis(id,20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    unLock(lockKey);
                }
            });
        }
        return shop;
    }

    //互斥锁方式，解决缓存击穿
    public Shop queryWithMutex(Long id){
        String key = CACHE_SHOP_KEY + id;
        String shopMessage = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopMessage)) {
            //JSON转对象
            Shop shop = JSONUtil.toBean(shopMessage, Shop.class);
            return shop;
        }
        if(shopMessage != null){
            return null;
        }
        //尝试获取锁
        String lockKey = null;
        Shop shop = null;
        try {
            lockKey = "local:shop:" + id;
            Boolean flag = tryLock(lockKey);
            if(!flag){
                Thread.sleep(50);
                queryWithMutex(id);
            }
            //模拟重建延时
            Thread.sleep(200);
            shop = getById(id);
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            //对象转JSON
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException();
        }finally {
            //释放锁
            unLock(lockKey);
        }
        return shop;
    }

    //获取锁
    public Boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //释放锁
    public void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    //封装逻辑过期时间
    public void saveShopRedis(Long id,Long expireSecond) throws InterruptedException {
        Shop shop = getById(id);
        Thread.sleep(200);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSecond));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData));
    }

    //缓存空对象方式，解决缓存穿透
    public Result queryWidthPassThrough(Long id){
        String key = CACHE_SHOP_KEY + id;
        String shopMessage = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopMessage)) {
            //JSON转对象
            Shop shop = JSONUtil.toBean(shopMessage, Shop.class);
            return Result.ok(shop);
        }
        if(shopMessage != null){
            return Result.fail("店铺信息不存在！");
        }
        Shop shop = getById(id);
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return Result.fail("店铺信息不存在哦！");
        }
        //对象转JSON
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

    @Override
    public Result update(Shop shop) {
        Long shopId = shop.getId();
        if (shopId == null) {
            return Result.fail("店铺的id不存在哦~");
        }
        updateById(shop);
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shopId);
        return Result.ok();
    }
}
